package com.jgp.glmeeting.mobile.controller;

import com.jgp.doc.model.FileInfo;
import com.jgp.doc.service.DocService;
import com.jgp.glmeeting.mobile.commons.BaseResponse;
import com.jgp.glmeeting.mobile.commons.ErrorMsg;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.List;

/**
 * 资料共享
 */
@RestController
@RequestMapping("mobile/MobileFileShareController")
public class MobileFileShareController {

    private final Logger logger = LoggerFactory.getLogger(MobileFileShareController.class);

    @Autowired
    private DocService docService;

    /**
     * 查询共享文件信息接口
     * @param meetingId
     * @return
     */
    @RequestMapping("queryFileInfos")
    public BaseResponse queryFileInfos(String meetingId) {
        if(StringUtils.isBlank(meetingId)){
            return new BaseResponse(ErrorMsg.INVALID_PARAM.getCode(), ErrorMsg.INVALID_PARAM.getErrorMsg());
        }
        try {
            BaseResponse baseResponse = new BaseResponse(200);
            List<FileInfo> fileInfoList = docService.queryFiles(meetingId, "com.jgp.glmeeting.model.Meeting");
            baseResponse.setObj(fileInfoList);
            return baseResponse;
        }catch (Exception e) {
            logger.error("查询共享文件信息接口异常,meetingId={}",meetingId,e);
            return new BaseResponse(ErrorMsg.SERVER_ERROR.getCode(), ErrorMsg.SERVER_ERROR.getErrorMsg());
        }

    }


    /**
     * 下载文件接口
     * @param fileId
     */
    @RequestMapping("downFile")
    public ResponseEntity downFile(String fileId){
        if(StringUtils.isBlank(fileId)){
            return new ResponseEntity(HttpStatus.NOT_FOUND);
        }
        try {
            fileId = fileId.substring(0, fileId.lastIndexOf("."));
            File file  = docService.queryIOFile(fileId);
            String dfileName = new String(file.getName().getBytes("utf-8"), "iso8859-1");
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", dfileName);
            return new ResponseEntity(FileUtils.readFileToByteArray(file), headers,
                    HttpStatus.CREATED);

        }catch (Exception e) {
            logger.error("查询共享文件信息接口异常,fileId={}",fileId,e);
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }

    }

}
